<?php
/**
 * Created by JetBrains PhpStorm.
 * User: TAO
 * Date: 13-3-28
 * Time: 下午6:24
 * To change this template use File | Settings | File Templates.
 */

$link = mysql_connect('localhost','root','123456');
mysql_select_db('students');

// get users
if($_REQUEST['action'] == 'read'){

    $sql = 'select * from student';

    $result = mysql_query($sql);

    $results = '';

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

        if($results == ""){
            $results = json_encode($row);
        }else{
            $results = $results.','.json_encode($row);
        }
    }
    $jsons = '{"success":true,"users":['.$results.']}';

    echo ($jsons);

// add user
}else if($_REQUEST['action'] == 'create'){

    $raw = '';
    $httpContent = fopen('php://input','r');
    while($kb = fread($httpContent,1024)){
        $raw .= $kb;
    }
    fclose($httpContent);

    $params = json_decode($raw);
    $name = formatStr($params -> name);
    $age = $params -> age;
    $phone = $params -> phone;

    $sql = 'insert into student(name,age,phone) values ("'.$name.'","'.$age.'","'.$phone.'")';

    $createResult = mysql_query($sql);

    if(! $createResult){
        echo('{"success":false,"message":"追加学生失败"}');
    }else{
        echo('{"success":true,"message":"追加学生成功"}');
    }

    // remove sutdent
}else if($_REQUEST['action'] == 'destroy'){

    $raw = '';
    $httpContent = fopen('php://input','r');
    while($kb = fread($httpContent,1024)){
        $raw .= $kb;
    }
    fclose($httpContent);

    $params = json_decode($raw);
    $id = $params -> Id;
    $name = formatStr($params -> name);
    $age = $params -> age;
    $phone = $params -> phone;

    $sql = "delete from student where id='".$id."'";

    $deleteResult = mysql_query($sql);
}
function formatStr($str){
    return trim(str_replace("'","''",$str));
}

?>